package com.example.esp8266.activity.productSQLlist;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.esp8266.activity.bean.Product;
import com.example.esp8266.activity.bean.ProductInfo;

import java.util.ArrayList;

/**
 * @Author lgd
 * @Date 2024/5/8 14:19
 */
public class ProductInfoHelper extends SQLiteOpenHelper {

    private final static String SQL_PERSON_id="create table productInfo" +
            "(_id integer primary key autoincrement,name text,price text,weight text,Total text,type text)";

    public ProductInfoHelper(Context context){
        super(context,"ProductInfo.db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(SQL_PERSON_id);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    //   添加 数据
    public void add(ProductInfo p){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",p.getName());
        values.put("price",p.getPrice());
        values.put("weight",p.getWeight());
        values.put("Total",p.getTotal());
        values.put("type",p.getType());
        db.insert("productInfo",null,values);
        db.close();
    }
    // 查找 全部
    public ArrayList<ProductInfo> selectAll(){
        ArrayList<ProductInfo> productInfoList = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = this.getReadableDatabase();
            cursor = db.query("productInfo", null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String price = cursor.getString(cursor.getColumnIndex("price"));
                    String weight = cursor.getString(cursor.getColumnIndex("weight"));
                    String Total = cursor.getString(cursor.getColumnIndex("Total"));
//                    String type = cursor.getString(cursor.getColumnIndex("type"));

                    productInfoList.add(new ProductInfo(id,name,price,weight,Total));
                    Log.d("Database", "----name------" + price + ", Price: " + price);
                } while (cursor.moveToNext());
            }
        } catch (SQLiteException e) {
            // 处理SQLite相关的异常
            Log.e("Database", "Error reading data from database", e);
        } finally {
            if (cursor != null) cursor.close();
            if (db != null && db.isOpen()) db.close();
        }
        return productInfoList;
    }


}
